package com.example.mybatis.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.*;
import java.util.Date;

/**
 * @program: qar-cloud
 * @description: 日期时间戳自动转换
 * @author: yyyyjinying
 * @create: 2023-10-30 22:37
 * 1.xml映射文件使用： <result property="createTime" column="create_time" jdbcType="TIMESTAMP" typeHandler="com.example.DateTypeHandler"/>
 * 2.mybaits-plus 方式： bean上添加注解：@TableName(autoResultMap = true)
 * @TableField(jdbcType = JdbcType.VARCHAR, typeHandler = DateTypeHandler.class)
 **/
public class DateautoTypeHandler extends BaseTypeHandler<Date> {

    // pojo转为jdbc
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
        preparedStatement.setTimestamp(i, new Timestamp(date.getTime()));
    }

    //jdbc转为pojo
    @Override
    public Date getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        Timestamp sqlTimestamp = resultSet.getTimestamp(columnName);

        if (sqlTimestamp != null) {
            return new Date(sqlTimestamp.getTime());
        }

        return null;
    }

    @Override
    public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return null;
    }

    @Override
    public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }
}
